/*
 * @Author: 姚京建
 * @Date: 2022-08-15 17:49:01
 * @LastEditors: 姚京建
 * @LastEditTime: 2022-08-19 15:41:17
 * @FilePath: /cms/src/utils/sign.js
 * @Description:
 */

import CryptoJS from 'crypto-js';
import sha256 from 'js-sha256';

function UUIDFastFun() {
  let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  let uuid = new Array(36);
  let rnd = 0;
  let r;
  for (let i = 0; i < 36; i++) {
    if (i == 8 || i == 13 || i == 18 || i == 23) {
      uuid[i] = '-';
    } else if (i == 14) {
      uuid[i] = '4';
    } else {
      if (rnd <= 0x02) rnd = (0x2000000 + Math.random() * 0x1000000) | 0;
      r = rnd & 0xf;
      rnd = rnd >> 4;
      uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
    }
  }
  return uuid.join('');
}

function encryptFun(word, keyStr) {
  keyStr = keyStr ? keyStr : 'abcdefgabcdefg12';
  let key = CryptoJS.enc.Utf8.parse(keyStr);
  let srcs = CryptoJS.enc.Utf8.parse(word);
  let encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
  return encrypted.toString();
}

/**
 * 参数签名
 * @param url
*/
export function getSignature(signConfig, data = '', prefix = '/api/') {
  const timestamp = signConfig.timestamp;
  const nonce = signConfig.nonce;
  const url = signConfig.url;
  let encrypt = '';
  let shaKey = data;
  let message = url.substring(url.indexOf(prefix), url.indexOf('?') === -1 ? url.length : url.indexOf('?'));
  let obj = {};
  let dic = [];
  let sort = {};
  if (/\?/.test(url)) {
    // 将url参数转成对象
    // message = message + '&' + url.substring(url.indexOf('?') + 1).split('&').sort().join('&');
    let urlArray = url.substring(url.indexOf('?') + 1).split('&');
    console.log('urlArray', urlArray)
    for (let i = 0, len = urlArray.length; i < len; i++) {
      if (urlArray[i]) {
        let urlItem = urlArray[i];
        let item = urlItem.split('=');
        obj[item[0]] = item[1];
      }
    }
    dic = Object.keys(obj).sort();
    for (let k in dic) {
      sort[dic[k]] = obj[dic[k]];
      message += '&' + dic[k] + '=' + obj[dic[k]];
    }

  }
  message = message.replace('&', '');

  shaKey = sha256.create().update(shaKey).hex();    // 用SHA256加密key
  shaKey = shaKey.substring(0, 32);                 // 截取加密后前32位字符

  encrypt = encryptFun(message, shaKey);
  console.log('第一步排序：', sort);
  // 第一步排序： {createdAtEnd: "2020-06-11", createdAtStart: "2020-06-10", limit: "10", orderNo: "YVcmech", orderType: "81471001", …}
  console.log('第二步排序拼接：', message);
  // 第二步排序拼接： /api/car/order/listcreatedAtEnd=2020-06-11&createdAtStart=2020-06-10&limit=10&orderNo=YVcmech&orderType=81471001&page=1
  console.log('用SHA256加密key====', shaKey);         // 用SHA256加密key==== 59953998e54a579be74c1b7344cd55c6
  console.log('第三步AES256转Base64：', encrypt);
  // 第三步AES256转Base64： PogCN3VP2yZLCoywfPsEGYYJw3hvXqKIWSO6RxGh+ojs2xvLS1HZPmhSuuaI2AurDM+zWYJ6xqFlPVF7Vhpl9R6rcFaUnDlcFm+A4na/p3fAjOK22oG3pYg2lo7uUbR3Rr/sl9I4fGytkLnVRit7pQVW/OTXO/CedgPM8y7mcgc=
  const arrSortJoin = [data, timestamp, nonce, encrypt].sort().join('');    // 'dktiDryj'为假数据，实际用 UUIDFast 重新生成
  console.log('第四步排序拼接：', arrSortJoin);
  // 第四步排序拼接：1593421947056N9WvzxhK1+K8mSxn+sMcWciidlYZcM70GTiliMqzpUjfHMVKGdUdc7CPuy1dEO4Zy5ZH2O1dBv0Wuyigsd6rpzg6h5f28YGMzlCeMtI0axyaqZTOzQiQozHU0lzTEva9cAeEbSUP+AWM/MNWrQgBfeCi5U5v522qCBQaSC5tOAo=dktiDryjtestsecret
  return sha256.create().update(arrSortJoin).hex();
  // console.log('SHA256得倒最终签名：', sign);
  // SHA256得倒最终签名：f53719faa865bb39a942b185d86b055f08214da903cdfc7c4573298c4638b03d
  // 第四步排序拼接：15922763992504hbQO2wFPogCN3VP2yZLCoywfPsEGYYJw3hvXqKIWSO6RxGh+ojs2xvLS1HZPmhSuuaI2AurDM+zWYJ6xqFlPVF7Vhpl9R6rcFaUnDlcFm+A4na/p3fAjOK22oG3pYg2lo7uUbR3Rr/sl9I4fGytkLnVRit7pQVW/OTXO/CedgPM8y7mcgc=testsecret
  //
  // }
}

export function getSignConfig(url) {
  const timestamp = Date.now();
  const nonce = UUIDFastFun();
  return {
    timestamp,
    nonce,
    url
  }
}
